package com.briup.es.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.briup.es.auth.SecurityUserContext;
import com.briup.es.domain.bean.Book;
import com.briup.es.domain.bean.Collect;
import com.briup.es.domain.vo.BookVO;
import com.briup.es.mapper.BookMapper;
import com.briup.es.service.CollectService;
import com.briup.es.mapper.CollectMapper;
import com.briup.es.util.BeanUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
@RequiredArgsConstructor
public class CollectServiceImpl extends ServiceImpl<CollectMapper, Collect>
        implements CollectService {

    private final BookMapper bookMapper;

    @Override
    public List<BookVO> listCollect() {
        // 获取当前登录用户的id
        Integer userId = SecurityUserContext.currentUserId();
        LambdaQueryWrapper<Collect> wrapper = new LambdaQueryWrapper<Collect>()
                .eq(Collect::getUserId, userId);
        List<Integer> bookIds = baseMapper.selectList(wrapper)
                .stream().map(Collect::getBookId).toList();

        LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<Book>()
                .in(Book::getId, bookIds);
        List<Book> books = bookMapper.selectList(queryWrapper);
        return BeanUtil.bean2VOS(books, BookVO.class);
    }

    @Override
    public void addCollect(Integer bookId) {
        Collect collect = new Collect();
        collect.setBookId(bookId);
        collect.setUserId(SecurityUserContext.currentUserId());
        baseMapper.insert(collect);
    }

    @Override
    public void batchCancelCollect(List<Integer> ids) {
        // 如果待删除收藏的id集合为空，直接返回
        if (CollectionUtils.isEmpty(ids)){
            return;
        }
        // 设置删除条件，并根据条件删除
        LambdaUpdateWrapper<Collect> wrapper = new LambdaUpdateWrapper<Collect>()
                .eq(Collect::getUserId, SecurityUserContext.currentUserId())
                .in(Collect::getBookId, ids);
        baseMapper.delete(wrapper);
    }
}